<?php

namespace plugin\ycMassage\app\admin\controller;

use app\common\builder\FormBuilder;
use app\common\builder\ListBuilder;
use app\common\service\UploadService;
use app\common\trait\SettingsTrait;
use FormBuilder\Factory\Elm;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageUserAgent;
use plugin\ycMassage\utils\enum\State;
use support\Request;
use think\facade\Db;

class AgentController extends BaseController
{
    use SettingsTrait;

    /**
     * 应用ID（null则获取系统配置）
     * @var int|null
     * @author 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    protected $saas_appid = null;

    /**
     * 构造函数
     * @return void
     * @author 贵州猿创科技有限公司
     * @copyright 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    public function initialize()
    {
        parent::initialize();
        $this->saas_appid = $this->request->saas_appid;
    }
    public function indexGetTable(Request $request)
    {
        $limit   = $request->get('limit', 20);
        $builder = new ListBuilder;
        $builder->addActionOptions('操作', [
            'width' => 160
        ]);
        $builder->addRightButton('edit', '编辑', [
            'api'    => $this->pluginPrefix . '/admin/Agent/update',
            'path' => '/Agent/update',
            'type'      => 'modal'
        ], [], [
            'type' => 'primary',
            'link' => true
        ]);
        $builder->addRightButton('wallet', '钱包', [
            'api'    => $this->pluginPrefix . '/admin/UserWallet/index',
            'path' => '/UserWallet/index',
            'aliasParams' => [
                'uid'
            ]
        ], [], [
            'type' => 'success',
            'link' => true
        ]);
        $builder->pageConfig([
            'pageSize' => $limit
        ]);
        $builder->addScreen('keywords', 'input', '搜索', [
            'placeholder' => '姓名、手机号搜索'
        ]);
        $builder->addScreen('state', 'select', '状态', [
            'options' => State::getOptions()
        ]);
        $builder->addScreen('regions', 'input', '地区', [
            'placeholder' => '地区模糊搜索'
        ]);
        $builder->addScreen('expire_time', 'select', '到期时间', [
            'options' => [
                ['label' => '永久', 'value' => 'permanent'],
                ['label' => '已到期', 'value' => 'expired'],
                ['label' => '即将到期(一月)', 'value' => 'expire_month'],
                ['label' => '即将到期(一周)', 'value' => 'expire_week'],
                ['label' => '即将到期(三天)', 'value' => 'expire_day'],
                ['label' => '即将到期', 'value' => 'will_expire'],
                ['label' => '未到期', 'value' => 'not_expire'],
            ]
        ]);
        $builder->addColumn('id', '序号', [
            'width' => 90
        ])
            ->addColumn('name', '姓名', [
                'width' => 120,
            ])
            ->addColumn('mobile', '手机号', [
                'width' => 120,
            ])
            ->addColumn('uid', 'UID', [
                'width' => 120,
            ])
            ->addColumn('nickname', '昵称', [
                'width' => 120,
            ])
            ->addColumnEle('headimg', '头像', [
                'width' => 60,
                'params' => [
                    'type' => 'image',
                ],
            ])
            ->addColumn('agent_level', '代理等级', [
                'width' => 140
            ])
            ->addColumn('commission_text', '分成比例', [
                'width' => 140
            ])
            ->addColumn('province', '省', [
                'width' => 120,
            ])
            ->addColumn('city', '市', [
                'width' => 120,
            ])
            ->addColumn('area', '区', [
                'width' => 120,
            ])
            ->addColumn('expire_time', '到期时间', [
                'width' => 160
            ])
            ->addColumnEle('state', '状态', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => State::dictOptions()
                ],
            ])
            ->addColumn('message', '状态备注', [
                'minWidth' => 120,
            ]);
        return $this->successRes($builder->create());
    }
    public function index(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $where = [
            ['a.saas_appid', '=', $request->saas_appid]
        ];
        $keywords = $request->get('keywords');
        if ($keywords) {
            $where[] = ['a.name|a.mobile', 'like', "%{$keywords}%"];
        }
        $regions = $request->get('regions');
        if ($regions) {
            $where[] = ['a.province|a.city|a.area', 'like', "%{$regions}%"];
        }
        $state = $request->get('state');
        if ($state !== null) {
            $where[] = ['a.state', '=', $state];
        }
        $expire_time = $request->get('expire_time');
        if ($expire_time) {
            switch ($expire_time) {
                case 'permanent':
                    $where[] = ['a.expire_time', '=', NULL];
                    break;
                case 'expired':
                    $where[] = ['a.expire_time', '<', date('Y-m-d H:i:s')];
                    break;
                case 'expire_month':
                    $where[] = ['a.expire_time', 'between', [date('Y-m-d H:i:s'), date('Y-m-d H:i:s', strtotime('+1 month'))]];
                    break;
                case 'expire_week':
                    $where[] = ['a.expire_time', 'between', [date('Y-m-d H:i:s'), date('Y-m-d H:i:s', strtotime('+1 week'))]];
                    break;
                case 'expire_day':
                    $where[] = ['a.expire_time', 'between', [date('Y-m-d H:i:s'), date('Y-m-d H:i:s', strtotime('+3 day'))]];
                    break;
                case 'will_expire':
                    $where[] = ['a.expire_time', 'between', [date('Y-m-d H:i:s'), date('Y-m-d H:i:s', strtotime('+1 month'))]];
                    break;
                case 'not_expire':
                    $where[] = ['a.expire_time', '>', date('Y-m-d H:i:s')];
                    break;
            }
        }
        $data = MassageUserAgent::where($where)
            ->alias('a')
            ->join('massage_user u', 'u.id=a.uid', 'LEFT')
            ->order('a.create_time desc')
            ->field('a.*,u.nickname,u.headimg')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])->each(function ($item) {
                if ($item->uid) {
                    $item->nickname = base64_decode($item->nickname);
                    if (strpos($item->headimg, 'http') !== 0) {
                        $item->headimg = UploadService::url($item->headimg);
                    }
                }
                if ($item->expire_time) {
                    if ($item->expire_time < date('Y-m-d H:i:s')) {
                        $item->expire_time = '已到期';
                    }
                } else {
                    $item->expire_time = '永久';
                }
                $item->commission_text = $item->commission > 0 ? $item->commission . '%' : '系统设置';
            });
        return $this->successRes($data);
    }
    public function update(Request $request)
    {
        $id = $request->get('id');
        $MassageUserAgent = MassageUserAgent::where(['id' => $id, 'saas_appid' => $request->saas_appid])->find();
        if (!$MassageUserAgent) {
            return $this->fail('数据不存在');
        }
        if ($request->method() === 'POST') {
            $D = $request->post();
            Db::startTrans();
            try {
                $MassageUserAgent->name = $D['name'];
                $MassageUserAgent->mobile = $D['mobile'];
                $MassageUserAgent->state = $D['state'];
                if ($MassageUserAgent->state == State::NO['value'] && isset($D['message'])) {
                    $MassageUserAgent->message = $D['message'];
                } else {
                    $MassageUserAgent->message = '';
                }
                if (!empty($D['expire_time'])) {
                    $MassageUserAgent->expire_time = $D['expire_time'] . ' 23:59:59';
                    if ($D['expire_time'] < date('Y-m-d H:i:s')) {
                        $MassageUserAgent->state = State::NO['value'];
                    }
                }
                if (empty($D['commission'])) {
                    $MassageUserAgent->commission = null;
                } else {
                    $MassageUserAgent->commission = $D['commission'];
                }
                $MassageUserAgent->save();
                Db::commit();
                return $this->success('审核成功');
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
        }
        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addRow('name', 'input', '姓名', '', [
            'col'           => 6,
        ]);
        $builder->addRow('mobile', 'input', '手机号', '', [
            'col'           => 18,
        ]);
        $builder->addComponent('agent_level', 'info', '意向代理等级', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('province', 'info', '省', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('city', 'info', '市', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('area', 'info', '区', '', [
            'col'           => 6,
        ]);
        $builder->addRow('state', 'radio', '状态', State::YES['value'], [
            'col' => 12,
            'options' => State::getOptions(),
            'control' => [
                [
                    'value' => State::NO['value'],
                    'where' => '==',
                    'rule' => [
                        Elm::textarea('message', '状态备注')
                            ->col([
                                'span' => 24
                            ])
                            ->props([
                                'filterable' => true,
                                'placeholder' => '状态备注',
                            ])
                    ],
                ],
            ]
        ]);
        $builder->addRow('expire_time', 'date', '到期时间', '', [
            'col' => 12,
            'props' => [
                'type' => 'date',
                'format' => 'YYYY-MM-DD',
                'value-format' => 'YYYY-MM-DD',
                'clearable' => true,
                'placeholder' => '请选择时间',
            ]
        ]);
        $builder->addRow('commission', 'number', '独立分成比例', '', [
            'col' => 12,
            'props' => [
                'prompt' => [
                    'text' => '佣金比例为0-100之间的整数，如设置为10，则代理佣金为订单金额的10%，0或不填：使用系统设置',
                ],
                'props' => [
                    'min' => 0,
                    'max' => 100,
                    'precision' => 0,
                ]
            ]
        ]);
        $MassageUserAgent->expire_time = $MassageUserAgent->expire_time ? date('Y-m-d', strtotime($MassageUserAgent->expire_time)) : '';
        $data = $builder->setData($MassageUserAgent)->create();
        return $this->successRes($data);
    }
}
